/*
 *  Copyright (C) 2010  Noxious Productions
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "map.hpp"

void Map::Draw(sf::RenderWindow &parent)
{
    // Just for testing. not done!
    // Must only draw the Tiles that are visible
    // add some argument with coords
    for (unsigned int i = 0, y = 0; i < myMap.size(); i++, y += 10)
        for (unsigned int j = 0, x = 0; j < myMap.at(i).size(); j++, x += 10)
            if (myMap.at(i).at(j))
            {
                sf::Sprite sprite(myMap.at(i).at(j)->GetImage(), sf::Vector2f((float)x, (float)y));
                parent.Draw(sprite);
            }
}

bool Map::LoadMap(const string &mapFilePath)
{
    XMLFile mapFile;
    if (!mapFile.LoadFile(mapFilePath))
        return false;

    if (!mapFile.SetActiveElement("Tiles"))
        return false; // handling here

    if (mapFile.SetActiveElement("Tile"))
    {
        do
        {
            Tile tile(mapFile.GetAttribute("src")); // create a new Tile object
            if (!tile.GetError())   // Check for errors
                myTiles.insert(pair<int, Tile>(mapFile.GetAttribute("key", 0), tile));  // insert the new Tile
        } while(mapFile.Next());
    }
    else 
        return false; // handling here: There can not be a map without a tile

    if (!mapFile.ResetToRoot())
        return false; // handling here

    if (!mapFile.SetActiveElement("Rows"))
        return false; // handling here

    if (mapFile.SetActiveElement("Row"))
    {
        do
        {
            istringstream stream(mapFile.GetText());    // TODO: Error handling for this?
            vector<Tile *> temp;    // create a Row
            int i;
            while (stream >> i)
            {
                map<int, Tile>::iterator it = myTiles.find(i);
                if (it != myTiles.end())
                    temp.push_back(&it->second);
                else
                    return false; // handling here
            }
            myMap.push_back(temp);  // write the Row to the vector
        } while(mapFile.Next());    // as long as there are rows
    }
    else
        return false; // handling here

    return true;
}
